package com.startdima.user.infrastructure.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.startdima.user.application.service.UserService;
import com.startdima.user.domain.entity.UserInfo;
import com.startdima.user.infrastructure.constant.BaseConstant;
import com.startdima.user.infrastructure.enums.LocaleEnum;
import com.startdima.user.infrastructure.exception.BusinessException;
import com.startdima.user.infrastructure.utils.JwtTokenUtil;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
 

@Service
@Slf4j
public class AppInterceptor implements HandlerInterceptor {

	@Autowired
	private JwtTokenUtil JwtTokenUtill;
	
	@Autowired
	private UserService userService;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        log.info("preHandle-------------------");
        //支持跨域访问设置
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isEmpty(token)) {
            throw new BusinessException(401, LocaleEnum.USER_NOT_LOGIN.name());
        }
        // 校验token时效性，检测是否过期
        JwtTokenUtill.checkTokenExpired(token);
        // 根据token获取用户信息
        UserInfo userInfo = userService.getUserByToken(token);
        // 校验token解析用户信息是否吻合
        JwtTokenUtill.validateToken(token, userInfo);
        log.info("[{}]用户请求系统", userInfo.getUsername());
        //保存用户登录的信息
        request.setAttribute(BaseConstant.LOGIN_USER_NAME, userInfo.getUsername());
        request.setAttribute(BaseConstant.LOGIN_USER_ID, userInfo.getUserId());
        request.setAttribute(BaseConstant.LOGIN_USER_TOKEN, token);
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("postHandle-------------------");
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("afterCompletion-------------------");
    }
    
}